using IMServer.Database;
using IMServer.Endpoints;

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

// 添加应用程序生命周期事件处理
app.Lifetime.ApplicationStopping.Register(async () =>
{
    Console.WriteLine("Application is shutting down...");
    await WebSocketManager.Instance.ShutdownAsync();
});

// 确保数据库初始化
try 
{
    var dbContext = MongoDBContext.Instance;
    Console.WriteLine("Database initialized successfully");
}
catch (Exception ex)
{
    Console.WriteLine($"Failed to initialize database: {ex.Message}");
    return;
}

// 添加错误处理中间件
app.Use(async (context, next) =>
{
    try
    {
        await next();

        // 处理 404 Not Found
        if (context.Response.StatusCode == 404)
        {
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsJsonAsync(new
            {
                Code = "4004",
                Message = $"路径 '{context.Request.Path}' 不存在"
            });
        }
    }
    catch (Exception ex)
    {
        // 处理其他未捕获的异常
        context.Response.StatusCode = 500;
        context.Response.ContentType = "application/json";
        await context.Response.WriteAsJsonAsync(new
        {
            Code = "5000",
            Message = $"服务器错误: {ex.Message}"
        });
    }
});

app.UseWebSockets();

app.MapGroup("/user/auth").MapUserAuthApi();
app.MapGroup("/user/query").MapUserQueryApi();  
app.MapGroup("/ws").MapWSEndpoint();
app.MapGroup("/friend").MapFriendApi();
app.MapGroup("/message").MapMessageApi();
app.MapGroup("/group").MapGroupApi();

// Specify the port to listen on port 8080
// app.Run("http://localhost:8080");
app.Run("http://0.0.0.0:8080");
